﻿#include "DAStandardNodeGraphicsItem.h"
#include <QPainter>
#include <QFontMetrics>
#include "DANodePalette.h"
#include "DAAbstractNode.h"
#include <QGraphicsScene>

class DAStandardNodeGraphicsItemPrivate
{
    DA_IMPL_PUBLIC(DAStandardNodeGraphicsItem)
public:
    DAStandardNodeGraphicsItemPrivate(DAStandardNodeGraphicsItem *p);
    QRectF _boundingRect;
    QRectF _nodeNameRect;
    QMarginsF _margins;
};
DAStandardNodeGraphicsItemPrivate::DAStandardNodeGraphicsItemPrivate(DAStandardNodeGraphicsItem *p)
    : q_ptr(p), _boundingRect(0, 0, 50, 50), _nodeNameRect(2, 2, 46, 46), _margins(10, 5, 10, 5)
{
}

DAStandardNodeGraphicsItem::DAStandardNodeGraphicsItem(DAAbstractNode *n, QGraphicsItem *p)
    : DAAbstractNodeGraphicsItem(n, p), d_ptr(new DAStandardNodeGraphicsItemPrivate(this))
{
}

DAStandardNodeGraphicsItem::~DAStandardNodeGraphicsItem() {}

void DAStandardNodeGraphicsItem::calcBoundingRect()
{
    prepareGeometryChange();
    DAAbstractNode *n = node();
    //先通过文本确定基本大小
    QGraphicsScene *sc = scene();

    if (sc) {
        QFontMetricsF fm(sc->font());
        d_ptr->_nodeNameRect = fm.boundingRect(n->metaData().getNodeName());
        d_ptr->_nodeNameRect.moveTo(0, 0);
    }
    d_ptr->_boundingRect = d_ptr->_nodeNameRect.marginsAdded(d_ptr->_margins);
    //再通过连接点确定是否满足
    int iks = qMax(n->getInputKeys().size(), n->getOutputKeys().size());
    qreal minHeight = 6 * iks + (iks + 1) * 3; //连接点高度6pix，间距最少3pix

    if (d_ptr->_boundingRect.height() < minHeight) {
        d_ptr->_boundingRect.setHeight(minHeight);
    }
    QPointF offset = -(d_ptr->_boundingRect.topLeft());

    d_ptr->_boundingRect.moveTo(0, 0);
    //在把nodename rect调整
    d_ptr->_nodeNameRect.moveTopLeft(offset);
    //最后重新计算连接点
    resetLinkPoint();
}

void DAStandardNodeGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->save();

    //绘制边框
    QPen pen(DANodePalette::getGlobalEdgeColor());
    QRectF rec = boundingRect();

    pen.setWidth(1);
    if (isSelected()) {
        pen.setWidth(2);
        pen.setColor(pen.color().darker());
        rec.adjust(1, 1, -1, -1);
    }
    painter->setPen(pen);
    painter->fillRect(rec, DANodePalette::getGlobalBackgroundColor());
    painter->drawRect(rec);
    //绘制文本
    painter->setPen(DANodePalette::getGlobalTextColor());
    painter->drawText(d_ptr->_nodeNameRect, Qt::AlignCenter, node()->getNodeName());
    //绘制连接点
    paintLinkPoints(painter, option, widget);
    painter->restore();
}

QRectF DAStandardNodeGraphicsItem::boundingRect() const
{
    return (d_ptr->_boundingRect);
}

QVariant DAStandardNodeGraphicsItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
    if (QGraphicsItem::ItemSceneHasChanged == change) {
        calcBoundingRect();
    }
    return (DAAbstractNodeGraphicsItem::itemChange(change, value));
}
